package v1

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"server/internal/model"
	"strconv"
)

func CreateRestfulMeau(c *gin.Context) {
	userinfo := GetUser(c)
	_ = c.Request.ParseForm()
	restful := &model.RestfulMeau{}
	_ = c.ShouldBind(restful)
	if len(restful.Name) == 0 {
		c.String(http.StatusOK, "接口名为空")
		return
	}
	go CreateLog(c, "API接口", "创建接口"+restful.Name)

	restful.OwnerID = userinfo.ID
	if restful.Father != 0 {
		restful.FatherID = &restful.Father
	}

	err := restful.Create()
	if err != nil {
		c.String(http.StatusOK, err.Error())
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"data": restful,
	})
}

func DeleteRestfulMeau(c *gin.Context) {
	restful := &model.RestfulMeau{}
	restful.Name = c.Param("name")
	if err := restful.Delete(); err != nil {
		c.String(http.StatusOK, err.Error())
		return
	}
	c.String(http.StatusOK, "目录删除成功")
}

func UpdateRestfulMeau(c *gin.Context) {
	restful := &model.RestfulMeau{}
	_ = c.ShouldBind(restful)
	if err := restful.Update(); err != nil {
		c.String(http.StatusOK, err.Error())
		return
	}
	c.String(http.StatusOK, "目录修改成功")
}

func QueryRestfulMeau(c *gin.Context) {
	restful := &model.RestfulMeau{}
	restful.Name = c.Param("name")
	if err := restful.Delete(); err != nil {
		c.String(http.StatusOK, err.Error())
		return
	}
	c.String(http.StatusOK, "目录删除成功")
}

func ListRestfulMeau(c *gin.Context) {
	var list []model.RestfulMeau
	restful := &model.RestfulMeau{}
	id := c.Query("id")
	if len(id) == 0 {
		id = "0"
	}
	father_id, err := strconv.Atoi(id)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"data": list,
		})
		return
	}
	if father_id == 0 {
		restful_list := restful.List(father_id)
		c.JSON(http.StatusOK, gin.H{
			"data": restful_list,
		})
	} else {
		restful.QueryById(father_id)
		c.JSON(http.StatusOK, gin.H{
			"data": restful,
		})
	}

}

func QueryRestfulMeauInfo(c *gin.Context) {
	restful := &model.RestfulMeau{}
	QueryByName(restful, c)
}
